package com.jtech.together.view.weight;

import android.content.Context;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import com.jtech.together.R;
import com.jtech.together.util.ImageUtils;
import com.jtech.together.view.adapter.ChatMessageAdapter;
import com.jtechlib2.view.JRecyclerView;
import com.jtechlib2.view.RefreshLayout;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.listener.MessagesQueryListener;
import cn.bmob.v3.exception.BmobException;

/**
 * 聊天消息列表
 * Created by wuxubaiyang on 2017/5/14.
 */

public class ChatListView extends CardView implements RefreshLayout.OnRefreshListener {
    @Bind(R.id.refreshlayout_chat_list)
    RefreshLayout refreshLayout;
    @Bind(R.id.jrecyclerview_chat_list)
    JRecyclerView jRecyclerView;
    @Bind(R.id.imageview_chat_list_background)
    ImageView imageViewBackground;

    private ChatMessageAdapter chatMessageAdapter;
    private BmobIMConversation conversation;

    public ChatListView(Context context) {
        this(context, null);
    }

    public ChatListView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ChatListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //初始化视图
        init();
    }

    /**
     * 初始化视图
     */
    private void init() {
        //获取主视图
        View contentView = LayoutInflater.from(getContext())
                .inflate(R.layout.view_chat_list, this, false);
        //设置主视图
        addView(contentView);
        //绑定视图
        ButterKnife.bind(this, contentView);
        //设置背景颜色
        setBackgroundColor(getContext().getResources().getColor(R.color.background));
        //设置layoutmanager
        jRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        //设置适配器
        chatMessageAdapter = new ChatMessageAdapter(getContext());
        jRecyclerView.setAdapter(chatMessageAdapter);
        //设置下拉刷新监听
        refreshLayout.setOnRefreshListener(this);
    }

    /**
     * 加载会话
     *
     * @param conversation
     */
    public void loadConversation(@NonNull BmobIMConversation conversation) {
        this.conversation = conversation;
        //首次拉取列表
        loadMessageList(false);
    }

    /**
     * 添加一条消息
     *
     * @param imMessage
     */
    public void addChatMessage(@NonNull BmobIMMessage imMessage) {
        //添加一条数据到列表中
        chatMessageAdapter.addData(imMessage);
        //滚动到最新一条消息
        scrollToLastMessage();
    }

    /**
     * 滚动到最新一条消息
     */
    public void scrollToLastMessage() {
        scrollToLastMessage(0);
    }

    /**
     * 一定延迟后滚动到最新消息
     *
     * @param delayMillis
     */
    public void scrollToLastMessage(long delayMillis) {
        if (chatMessageAdapter.getItemCount() > 0) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    jRecyclerView.smoothScrollToPosition(chatMessageAdapter.getItemCount() - 1);
                }
            }, delayMillis);
        }
    }

    /**
     * 显示聊天列表的背景图片
     *
     * @param imageUrl
     */
    public void setChatListBackground(@NonNull String imageUrl) {
        ImageUtils.showImage(getContext(), imageUrl, imageViewBackground);
    }

    /**
     * 设置聊天列表监听
     *
     * @param chatMessageListener
     */
    public void setChatMessageListener(ChatMessageAdapter.ChatMessageListener chatMessageListener) {
        chatMessageAdapter.setChatMessageListener(chatMessageListener);
    }

    /**
     * 加载消息列表
     *
     * @param isPullRefresh
     */
    private void loadMessageList(final boolean isPullRefresh) {
        if (null != conversation) {
            conversation.queryMessages(chatMessageAdapter.getItemCount() > 0 ? chatMessageAdapter.getItem(0) : null,
                    chatMessageAdapter.getDisplayNumber(), new MessagesQueryListener() {
                        @Override
                        public void done(List<BmobIMMessage> list, BmobException e) {
                            refreshLayout.refreshingComplete();
                            if (null == e && list.size() > 0) {
                                chatMessageAdapter.addDatas(0, list);
                                if (!isPullRefresh) {
                                    scrollToLastMessage();
                                }
                            }
                        }
                    });
        }
    }

    @Override
    public void onRefresh() {
        loadMessageList(true);
    }
}